<template>
	<view>
		<view style="background-color: #fff">
			<!-- <view class="row">
				<view class="date col" style="color: #007AFF;">选择日期范围</view>
			</view> -->
			<!-- <view class="row">
				<view class="date col" style="color: #FF0000;">注意：订餐日期首尾背景色为蓝色，表示开始和结束！</view>
			</view> -->
			<!-- :end-date="getFinallyDates" -->
			<!-- <uni-calendar :insert="true" :lunar="true" :range="true" :start-date="getDateDay" @change="change" /> -->
			<uni-calendar :insert="true" :date="getDateDay" :lunar="true" :range="false" :start-date="getDateDay"
				:selected="selectedDates" @change="change" @monthSwitch="onChangeMonth" />
		</view>
		<!-- <view class="row">
			<view class="date col" style="color: #007AFF;">开始时间：{{selectedRange[0] ? selectedRange[0] : ''}}</view>
			<view class="date col" style="color: #007AFF;">结束时间：{{selectedRange[1] ? selectedRange[1] : ''}}</view>
		</view> -->
		<!-- 全选/反选 -->
		<view class="row" v-if="fooddietlist.length > 0">
			<view class="date col">日期</view>
			<block v-for="(menu, mIndex) in menu" :key="mIndex">
				<view class="menu col">
					{{ menu.name }}
				</view>
			</block>
		</view>
		<view class="row" v-for="(item,index) in fooddietlist" :key="index">
			<view class="date col">
				{{item.dutyDate}}
				<view style="color: #006400;">{{item.ncWeek}}</view>
			</view>
			<block v-for="(val, key, i) in item" :key="i">
				<template v-if="key != 'dutyDate' && key != 'ncWeek'">
					<view class="menu col" @click="_isAllselect(key,val,index,item.dutyDate)">
						<uni-icons type="checkbox-filled" size="30" color="#007AFF" v-if="val"></uni-icons>
						<uni-icons type="circle" size="30" v-else></uni-icons>
					</view>
				</template>
			</block>
		</view>
		<view style="height: 160rpx;"></view>
		<view class="toolbars">
			<view class="toolleft">
				<view class="tlefti" @click="selectAllBreakfast">
					<template>
						<uni-icons type="checkbox-filled" size="30" color="#007AFF" v-if="breakfastOrdered"></uni-icons>
						<uni-icons type="circle" size="30" v-else></uni-icons>
					</template>
					<text>全选早餐</text>
				</view>
				<view class="tlefti" @click="selectAllLunch">
					<template>
						<uni-icons type="checkbox-filled" size="30" color="#007AFF" v-if="lunchOrdered"></uni-icons>
						<uni-icons type="circle" size="30" v-else></uni-icons>
					</template>
					<text>全选中餐</text>
				</view>
				<view class="tlefti" @click="selectAllDinner">
					<template>
						<uni-icons type="checkbox-filled" size="30" color="#007AFF" v-if="dinnerOrdered"></uni-icons>
						<uni-icons type="circle" size="30" v-else></uni-icons>
					</template>
					<text>全选晚餐</text>
				</view>
			</view>
			<view class="button-grounp">
				<view class="button payment-button" @tap="submit">
					立即报餐
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		postFoodDietList, // 获取报餐信息
		postTaskList, // 提交报餐
	} from "@/proxy/food/food.api.js";

	import {
		// getFinallyDate,
		// getDateTomorrows,
		getDateTomorrow,
		// getHourMinute
	} from "@/utils/dateTime";

	export default {
		data() {
			return {
				breakfastOrdered: false,
				lunchOrdered: false,
				dinnerOrdered: false,
				// 早中晚餐名称数组
				menu: [{
						name: "早餐"
					},
					{
						name: "中餐"
					},
					{
						name: "晚餐"
					},
				],
				// 时间数组，保存每天的时间数据
				days: [],
				getDateDay: getDateTomorrow(), // 当月明天
				// getFinallyDates: getFinallyDate(), // 当月最后一天
				name: "", // 报餐人
				jobNumber: "", // 报餐工号
				fooddietlist: [], // 获取报餐信息
				isfive: false,
				// selectedRange:[], // 选择的日期范围
				selectedDates: []
			};
		},
		async onShow() {
			// this.isDateFive();
			// 获取当前日期
			const currentDate = new Date();
			const year = currentDate.getFullYear();
			const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // getMonth() 返回的是0-11，所以加1
			const formattedDate = `${year}-${month}`;
			this.dateValue = formattedDate;
			const {
				firstDay,
				lastDay
			} = this.getMonthFirstAndLastDay(formattedDate);
			this.startDate = firstDay;
			this.endDate = lastDay;

			const {
				name,
				jobNumber
			} = uni.getStorageSync("userInfo");
			this.name = name;
			this.jobNumber = jobNumber;

			await this.postFoodDietListData();
		},
		methods: {
			selectAllBreakfast() {
				this.breakfastOrdered = !this.breakfastOrdered;
				this.fooddietlist.forEach(item => {
					if (!this.isTodayAndAfter('breakfastOrdered', item.dutyDate)) {
						item.breakfastOrdered = this.breakfastOrdered ? 1 : 0;
					}
				});
			},
			selectAllLunch() {
				this.lunchOrdered = !this.lunchOrdered;
				this.fooddietlist.forEach(item => {
					if (!this.isTodayAndAfter('lunchOrdered', item.dutyDate)) {
						item.lunchOrdered = this.lunchOrdered ? 1 : 0;
					}
				});
			},
			selectAllDinner() {
				this.dinnerOrdered = !this.dinnerOrdered;
				this.fooddietlist.forEach(item => {
					if (!this.isTodayAndAfter('dinnerOrdered', item.dutyDate)) {
						item.dinnerOrdered = this.dinnerOrdered ? 1 : 0;
					}
				});
			},
			getMonthFirstAndLastDay(dateStr) {
				// 将传入的年月字符串转为日期对象
				const [year, month] = dateStr.split('-').map(Number);

				// 获取该月的第一天
				const firstDay = new Date(year, month - 1, 1);

				// 获取该月的最后一天
				const lastDay = new Date(year, month, 0); // 月份+1，再设置天数为0，即得到上个月的最后一天

				// 格式化为 "yyyy-mm-dd"
				const formatDate = (date) => {
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					return `${year}-${month}-${day}`;
				};

				return {
					firstDay: formatDate(firstDay),
					lastDay: formatDate(lastDay)
				};
			},
			// 切换月份
			async onChangeMonth(e) {
				const dateStr = e.year + "-" + e.month;
				const {
					firstDay,
					lastDay
				} = this.getMonthFirstAndLastDay(dateStr);
				this.startDate = firstDay;
				this.endDate = lastDay;
				await this.postFoodDietListData();
			},
			// 获取订餐详情
			async postFoodDietListData() {
				let that = this;
				try {
					// 用户点击确认后执行的异步操作
					const result = await postFoodDietList({
						in: that.startDate,
						out: that.endDate,
						name: that.name, // 人
						jobNumber: that.jobNumber, // 
					});

					// console.log("报餐任务结果", result);
					if (result.code == 200) {
						// 提交成功后的操作
						// this.fooddietlist = result.data;
						result.data.map((item, index) => {
							// 检查是否有任何一个特定的属性值为 1
							if (item.breakfastOrdered === 1 || item.dinnerOrdered === 1 || item
								.lunchOrdered === 1) {
								// 特殊处理部分
								// console.log("特殊处理：有一个餐已被点餐！");
								// 在此处添加您需要的特殊处理逻辑
								that.selectedDates.push({
									date: item.dutyDate, // 订餐日期yyyy-mm-ss
									type: 1,
									info: '已订',
									dutyDate: item.dutyDate,
									breakfastOrdered: item.breakfastOrdered,
									lunchOrdered: item.lunchOrdered,
									dinnerOrdered: item.dinnerOrdered
								});
							} else {
								that.selectedDates.push({
									date: item.dutyDate, // 订餐日期yyyy-mm-ss
									type: 3,
									info: '未订',
									dutyDate: item.dutyDate,
									breakfastOrdered: item.breakfastOrdered,
									lunchOrdered: item.lunchOrdered,
									dinnerOrdered: item.dinnerOrdered
								});
							}
						})

					} else {
						this.$toast({
							title: result.data.msg,
						});
					}

				} catch (err) {
					this.$toast({
						icon: 'none',
						title: '发起失败，请联系管理员！',
						duration: 2000
					});
					console.log(err);
				}
			},
			// 判断是否过了当天五点
			// isDateFive() {
			// 	// 获取当前日期
			// 	const currentDate = new Date();
			// 	// currentDate.setHours(8, 59, 59, 59); // 设置为当天09:00 AM
			// 	// currentDate.setHours(9, 0, 0, 0); // 设置为当天09:00 AM
			// 	// 获取当前时间戳
			// 	const currentTimestamp = currentDate.getTime();

			// 	// 获取当天5:00 AM的时间戳
			// 	const fiveAM = new Date(currentDate);
			// 	fiveAM.setDate(currentDate.getDate()); // 将日期设置为明天
			// 	fiveAM.setHours(7, 0, 0, 0); // 设置为当天07:00 AM
			// 	const fiveAMTimestamp = fiveAM.getTime(); // 获取当天07:00 AM的时间戳

			// 	// 判断是否已过当天07:00 AM
			// 	if (currentTimestamp >= fiveAMTimestamp) {
			// 		// console.log("已过当天07:00")
			// 		this.getDateDay = getDateTomorrows();
			// 	} else {
			// 		// console.log("未过当天07:00")
			// 		this.getDateDay = getDateTomorrow();
			// 	}
			// },
			// 选择时间获取订餐详情
			async change(event) {
				const selectedDate = event.fulldate;
				const index = this.selectedDates.findIndex(item => item.date === selectedDate);
				const indexs = this.fooddietlist.findIndex(item => item.dutyDate === selectedDate);
				const ncWeek = event.lunar.ncWeek;
				const {
					dutyDate,
					breakfastOrdered,
					lunchOrdered,
					dinnerOrdered
				} = this.selectedDates[index];
				// 如果日期已存在，移除它；如果不存在，则添加它
				if (indexs === -1) {
					this.selectedDates[index].type = 0;
					this.selectedDates[index].info = '预订';
					this.fooddietlist.push({
						dutyDate: dutyDate,
						ncWeek: ncWeek,
						breakfastOrdered: breakfastOrdered,
						lunchOrdered: lunchOrdered,
						dinnerOrdered: dinnerOrdered,
					})
				} else {
					if (breakfastOrdered === 1 || dinnerOrdered === 1 || lunchOrdered === 1) {
						this.selectedDates[index].type = 1;
						this.selectedDates[index].info = '已订';
					} else {
						this.selectedDates[index].type = 3;
						this.selectedDates[index].info = '未订';
					}
					this.fooddietlist.splice(indexs, 1);
				}

				// const selectedDates = event.range.data;

				// // 如果选择了两个日期，确保第一个日期小于第二个日期
				// if (selectedDates.length >= 1) {
				// 	// 比较选择的日期，确保顺序正确
				// 	if (new Date(selectedDates[0]) > new Date(selectedDates[selectedDates.length - 1])) {
				// 		// 如果第一个日期大于第二个日期，交换它们
				// 		this.selectedRange = [selectedDates[selectedDates.length - 1], selectedDates[0]];
				// 	} else {
				// 		// 否则直接使用选中的日期
				// 		this.selectedRange = [selectedDates[0],selectedDates[selectedDates.length - 1]];
				// 	}
				// } else {
				// 	// 只选择了一个日期，设置为开始日期
				// 	this.selectedRange = [e.range.before, ''];
				// }

				// if (this.selectedRange[0] && this.selectedRange[1]) {
				// 	try {
				// 		// 执行的异步操作
				// 		const result = await postFoodDietList({
				// 			in: this.selectedRange[0], //订餐开始yyyy-MM-dd
				// 			out: this.selectedRange[1], //订餐结束yyyy-MM-dd
				// 			name: this.name, // 报餐人
				// 			jobNumber: this.jobNumber, // 报餐工号
				// 		});

				// 		console.log("批量报餐结果", result);
				// 		if (result.code == 200) {
				// 			this.fooddietlist = result.data;
				// 		} else {
				// 			this.$toast({
				// 				title: result.data.msg,
				// 			});
				// 		}

				// 	} catch (err) {
				// 		// 捕获用户取消或者提交失败的错误
				// 		this.$toast({
				// 			icon: 'none',
				// 			title: '发起失败，请联系管理员！',
				// 			duration: 2000
				// 		});
				// 		console.log(err);
				// 	}

				// }

			},
			// getClientList() {
			// 	this.selectedDates = [];
			// 	this.fooddietlist = [];
			// 	uni.navigateTo({
			// 		url: '/pagesMeal/baocan/log'
			// 	})
			// },
			// 提交报餐
			async submit() {
				let that = this;

				if (that.fooddietlist.length === 0) {
					return that.$toast({
						title: "订餐日期不可为空",
					});
				}

				// if (!this.selectedRange[0] || !this.selectedRange[1]) {
				// 	return this.$toast({
				// 		title: "开始和结束时间不能为空",
				// 	});
				// }

				// if(!that.breakfastOrdered && !that.lunchOrdered && !that.dinnerOrdered){
				// 	return this.$toast({
				// 	    title: "订餐类型不可为空",
				// 	});
				// }

				// 将 uni.showModal 封装为 Promise
				const confirmSubmit = () => {
					return new Promise((resolve, reject) => {
						uni.showModal({
							title: '确认提交',
							content: '你确定要提交报餐吗？',
							success: function(res) {
								if (res.confirm) {
									resolve(); // 用户点击确认，继续执行提交操作
								} else if (res.cancel) {
									reject('用户取消提交'); // 用户点击取消，返回失败
								}
							}
						});
					});
				};

				try {
					// 等待用户确认
					await confirmSubmit();

					// 用户点击确认后执行的异步操作
					const result = await postTaskList({
						// ordermealsStart: that.ordermealsStart, //订餐开始yyyy-MM-dd
						// ordermealsEnd: that.ordermealsEnd, //订餐结束yyyy-MM-dd
						// breakfastOrdered: that.breakfastOrdered, //早餐报餐（0表示不订餐，1表示订餐）
						// lunchOrdered: that.lunchOrdered, //中餐报餐
						// dinnerOrdered: that.dinnerOrdered, //晚餐报餐
						name: that.name, // 报餐人
						jobNumber: that.jobNumber, // 报餐工号
						dietDaily: that.fooddietlist, // 提交报餐数据
					});

					console.log("批量报餐结果", result);
					if (result.code == 200) {
						// 提交成功后的操作
						that.$toast({
							title: "报餐成功",
						});
						that.selectedDates = [];
						that.fooddietlist = [];
						var nav = setTimeout(() => {
							uni.navigateTo({
								url: '/pagesMeal/baocan/log',
								success() {
									clearTimeout(nav)
								}
							})
						}, 500)
					} else {
						that.$toast({
							title: result.data.msg,
						});
					}

				} catch (err) {
					// 捕获用户取消或者提交失败的错误
					if (err === '用户取消提交') {
						console.log('用户取消提交');
					} else {
						that.$toast({
							icon: 'none',
							title: '发起失败，请联系管理员！',
							duration: 2000
						});
						console.log(err);
					}
				}
			},
			isTodayAndAfter(key, inputDate) {
				// 获取当前日期和时间
				const now = new Date();

				// 获取传入的日期，假设格式是 'YYYY-MM-DD'
				const input = new Date(inputDate);

				// 比较日期部分（不考虑时间部分），判断是否是今天
				const isToday = now.getFullYear() === input.getFullYear() &&
					now.getMonth() === input.getMonth() &&
					now.getDate() === input.getDate();

				// 获取当前的时间，判断是否超过
				const hours = now.getHours();
				const minutes = now.getMinutes();
				let isAfter = false;

				switch (key) {
					case "breakfastOrdered":
						// 判断是否已过08:30
						// isAfter = (hours > 8) || (hours === 8 && minutes >= 30);
						isAfter = isToday;
						break;
					case "lunchOrdered":
						// 判断是否已过12:00
						isAfter = (hours > 9) || (hours === 9 && minutes >= 0);
						break;
					case "dinnerOrdered":
						// 判断是否已过18:00
						isAfter = (hours > 15) || (hours === 15 && minutes >= 0);
						break;
				}

				// 返回是否是今天且是否超过指定时间
				return isToday && isAfter;
			},
			// 改变状态
			_isAllselect(key, val, index, dutyDate) {
				const status = val === 1 ? 0 : 1; // 反选状态
				// this.menu_Array[key] = status; // 更新全选/反选状态
				// this.fooddietlist[index][key] = status; // 更新全选/反选状态
				let that = this;
				let result = false;
				switch (key) {
					case "breakfastOrdered":
						result = this.isTodayAndAfter(key, dutyDate);
						if (result) {
							// console.log("传入日期是今天，并且已经过了08:30");
							return that.$modal({
								title: '提示',
								content: `早餐已到当天，不可再订`,
								showCancel: false, // 如果不需要取消按钮
								confirmText: '知道了'
							});
						} else {
							// console.log("传入日期不是今天，或者还没有过08:30");
							this.fooddietlist[index][key] = status; // 更新全选/反选状态
						}
						break;
					case "lunchOrdered":
						result = this.isTodayAndAfter(key, dutyDate);
						if (result) {
							// console.log("传入日期是今天，并且已经过了12:00");
							return that.$modal({
								title: '提示',
								content: `中餐已过9:00，不可再订`,
								showCancel: false, // 如果不需要取消按钮
								confirmText: '知道了'
							});
						} else {
							// console.log("传入日期不是今天，或者还没有过12:00");
							this.fooddietlist[index][key] = status; // 更新全选/反选状态
						}
						break;
					case "dinnerOrdered":
						result = this.isTodayAndAfter(key, dutyDate);
						if (result) {
							// console.log("传入日期是今天，并且已经过了18:00");
							return that.$modal({
								title: '提示',
								content: `晚餐已过15:00，不可再订`,
								showCancel: false, // 如果不需要取消按钮
								confirmText: '知道了'
							});
						} else {
							// console.log("传入日期不是今天，或者还没有过18:00");
							this.fooddietlist[index][key] = status; // 更新全选/反选状态
						}
						break;
				}
			},
		},
	};
</script>


<style lang="scss" scoped>
	.row {
		display: flex;
		padding: 30rpx;
		border-bottom: 1px solid #ececec;
		align-items: center;

		.col {
			flex: 1;
			text-align: center;
			font-size: 29rpx;
		}
	}

	.op {
		display: flex;
		padding: 20rpx 0;
		justify-content: flex-end;
		padding-right: 4%;
	}

	.btn {
		text-align: center;
		padding: 20rpx 40rpx;
		border-radius: 20rpx;
	}

	.check-all {
		background-color: #0ac125;
		color: #fff;
	}

	.form {
		background-color: #ffffff;
		padding: 0rpx 4% 20rpx 4%;

		.item {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0 20rpx 0;
			align-items: center;
		}

		.checkbox {
			display: flex;
			align-items: center;
		}

		.input {
			text-align: right;
		}

		.border-bt {
			border-bottom: 1px solid #ececec;
		}
	}

	// 吸底工具栏
	.toolbars {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		// bottom: var(--window-bottom);
		padding-bottom: constant(safe-area-inset-bottom, 0);
		padding-bottom: env(safe-area-inset-bottom, 0);
		z-index: 999999;
		height: 100rpx;
		display: flex;
		// padding: 0 15rpx;
		padding-left: 15rpx;
		padding-right: 15rpx;
		align-items: center;
		border-top: 1rpx solid #ededed;
		border-bottom: 1rpx solid #ededed;
		background-color: #fff;
		box-sizing: content-box;

		.toolleft {
			font-size: 27rpx;
			display: flex;
			align-items: center;

			.tlefti {
				display: flex;
				align-items: center;
			}
		}

		.button-grounp {
			margin-left: auto;
			display: flex;
			justify-content: space-between;
			text-align: center;
			line-height: 72rpx;
			font-size: 13px;
			color: #fff;

			.button {
				width: 200rpx;
				border-radius: 72rpx;
			}

			.payment-button {
				background-color: #0081ff;

				&.disabled {
					opacity: 0.6;
				}
			}
		}
	}
</style>